import { WhiteScreenDetector } from "./white-screen-detector"

export class WhiteScreen {
    private detector: WhiteScreenDetector | null = null
    private lastReportTime = 0
    private readonly REPORT_INTERVAL = 5000
    private reportCount = 0
    private readonly MAX_REPORT_COUNT = 3
    private consecutiveErrors = 0
    private readonly MAX_CONSECUTIVE_ERRORS = 5

    constructor(
        private monitor: any,
        private options: any = {}
    ) {
        this.detector = new WhiteScreenDetector(
            result => {
                if (result.status === "error") {
                    this.consecutiveErrors++
                    if (this.consecutiveErrors >= this.MAX_CONSECUTIVE_ERRORS) {
                        this.reportWhiteScreen(result, true)
                    } else {
                        this.reportWhiteScreen(result, false)
                    }
                } else {
                    this.consecutiveErrors = 0
                    this.reportCount = 0
                }
            },
            {
                ...this.options,
                watchRouteChanges: true // 确保启用路由监听
            }
        )
        this.start()
    }

    public start(): void {
        this.detector?.start()
    }

    public stop(): void {
        if (this.detector) {
            this.detector.stop()
            this.detector = null
        }
        this.consecutiveErrors = 0
        this.reportCount = 0
    }

    private reportWhiteScreen(result: any, isCritical: boolean): void {
        const now = Date.now()

        if (isCritical) {
            this.forceReport(result)
            return
        }

        if (this.reportCount < this.MAX_REPORT_COUNT && (this.reportCount === 0 || now - this.lastReportTime >= this.REPORT_INTERVAL)) {
            this.forceReport(result)
        }
    }

    private forceReport(result: any): void {
        this.lastReportTime = Date.now()
        this.reportCount++

        const data = {
            type: "blank-screen",
            ...result,
            time: Date.now(),
            pageUrl: window.location.href,
            viewport: {
                width: window.innerWidth,
                height: window.innerHeight
            },
            metadata: {
                reportCount: this.reportCount,
                consecutiveErrors: this.consecutiveErrors
            }
        }

        this.monitor.transport?.sendBlankScreen(data)
    }
}
